<template>
	<!-- 编辑弹出框 -->
	<el-dialog :title="dialogTitle" v-model="dialogVisible" align-center width="50%" top="30vh" @close="handleClose">
		<el-form ref="theFormRef" :model="dataForm" label-width="70px">
			<el-form-item label="ID"><el-input v-model="dataForm.id" :disabled="true"></el-input></el-form-item>
			<el-form-item label="名称"><el-input v-model="dataForm.name"></el-input></el-form-item>
			<el-form-item label="排序"><el-input v-model="dataForm.sort"></el-input></el-form-item>
			<el-form-item label="图片"><upload-single-image v-model="dataForm.img"></upload-single-image></el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleSubmit">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup>
import * as CategoryAPI from '@/api/category.js';
import UploadSingleImage from '@/components/Upload/UploadSingleImage.vue';
import { ref, computed, nextTick, defineEmits, defineExpose } from 'vue';
import { ElMessage, ElNotification } from 'element-plus';

const dialogVisible = ref(false);
const dataForm = ref({ id: 0 });
//声明一个模板中DOM元素的引用, 必须和模板里的 ref 同名
const theFormRef = ref(null);
const emit = defineEmits(['refreshDataList']);

const dialogTitle = computed(() => {
	return !dataForm.value.id ? '新增' : '编辑';
});

const init = async (id) => {
	dataForm.value.id = id || 0;
	dialogVisible.value = true;
	await nextTick();
	theFormRef.value.resetFields(); 
	if (id) {//是编辑
		let result = await CategoryAPI.getDetailById(id);
		dataForm.value = result.data; //看接口文档，知道data是对应的用户对象
	} else {//是新增
		setDataFormToDefault();
	}
};

const handleSubmit = () => {
	theFormRef.value.validate(async valid => {
		if (valid) {
			await CategoryAPI.save(dataForm.value);
			ElMessage.success(`保存成功`);
			dialogVisible.value = false;
			emit('refreshDataList'); //重新刷新列表数据
		}
	});
};

const setDataFormToDefault = () => {
	//初始默认值
	let defaultForm = {};
	defaultForm.id = 0;
	defaultForm.name = '';
	dataForm.value = Object.assign({}, defaultForm);
};

const handleClose = () => {
	ElNotification({
		title: '警告',
		message: '图片文件上传到云存储后，如果有没有使用的？,考虑删除了吗？..........',
		type: 'warning'
	});
};

//暴露接口方法
defineExpose({
	init
});
</script>

<style scoped>
.dialog-footer button:first-child {
	margin-right: 10px;
}
</style>
